package com.example.demo.controller;

import com.example.demo.comm.ApiJsonResp;
import com.example.demo.dto.SchoolCode.AddSchoolCodeRequestDTO;
import com.example.demo.model.SchoolCode;
import com.example.demo.service.SchoolCodeService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/SchoolCode")
public class SchoolCodeController {

    @Autowired
    private SchoolCodeService schoolCodeService;
    @GetMapping("/getList")
    public ApiJsonResp<?> getList(){
        ApiJsonResp<?> resp = new ApiJsonResp<>();

        resp.setData(schoolCodeService.GetAllList().toArray());
        resp.IsOK();
        return resp;
    }

    @PostMapping("/add")
    public ApiJsonResp<?> add(@RequestBody @Valid AddSchoolCodeRequestDTO requestDTO, BindingResult bindingResult){
        ApiJsonResp<?> resp = new ApiJsonResp<>();

        // todo is not exfact
        if (bindingResult.hasErrors()) {
            System.out.println(11111);
            // 获取第一个验证错误
            FieldError fieldError = bindingResult.getFieldErrors().get(0);

            // 获取字段名和错误消息
            String fieldName = fieldError.getField();
            String errorMessage = fieldError.getDefaultMessage();
            resp.IsErr("Validation failed for field '" + fieldName + "': " + errorMessage);
            return resp;
        }

        SchoolCode sc = SchoolCode
                .builder()
                .code(requestDTO.getCode())
                .school_name(requestDTO.getSchoolName())
                .build();
        Integer newId = schoolCodeService.AddSchoolCode(sc);

        resp.setData(newId);
        resp.IsOK();
        return resp;
    }
    @PostMapping("/update")
    public ApiJsonResp<?>  update() {

        ApiJsonResp<?> resp = new ApiJsonResp<>();
        resp.IsOK();
        return resp;
    }
}
